package com.wnnight.wys.security;

import com.wnnight.wys.entity.role.MenuPerm;
import com.wnnight.wys.exception.ValidateException;
import com.wnnight.wys.mapper.role.MenuPermMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;

import java.util.ArrayList;
import java.util.List;

@Slf4j
public class JwtVerifyProvider implements AuthenticationProvider {
    @Autowired
    private JwtUtils jwtUtils;

    @Autowired
    private MenuPermMapper menuPermMapper;


    @Override
    public Authentication authenticate(Authentication authentication) throws AuthenticationException {
        JwtToken jwtToken = (JwtToken) authentication;
        String jwt = (String) jwtToken.getPrincipal();
        if (jwt == null) {
            throw new ValidateException("令牌无效");
        }
        List<SimpleGrantedAuthority> authorities = new ArrayList<>();
        if (jwtUtils.verifyJWT(jwt)) {
            int roleId = (int) JwtUtils.getInfo(jwt, "roleId");
            List<MenuPerm> perms = menuPermMapper.getByRoleId(roleId);
            for (MenuPerm perm : perms) {
                if (perm.getPerms()!= null) {
                    authorities.add(new SimpleGrantedAuthority(perm.getPerms())); //权限标识
                }
            }
            //产生已认证的JwtToken
            JwtToken authenticatedToken = new JwtToken(jwt, true, authorities);
            //保存起来
            SecurityContextHolder.getContext().setAuthentication(authenticatedToken);
            return authenticatedToken;
        } else {
            throw new ValidateException("令牌无效");
        }
    }

    @Override
    public boolean supports(Class<?> authentication) {
        return JwtToken.class.isAssignableFrom(authentication);
    }
}
